﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;
using System.Threading;
using System.Threading.Tasks;

namespace aspnet_server_push.MicroBlog
{
    public class MicroBlogServer:Hub, IDisconnect
    {
        private static Dictionary<string, bool> cancelQueue = new Dictionary<string, bool>();

        public void RefreshTimeline(string uid)
        {
            cancelQueue.Add(this.Context.ConnectionId, false);

            var msgTask = new Task(new Action<object>(PushUserMessage), uid);
            msgTask.Start();
            
        }


        private void PushUserMessage(object uid)
        {
            while (true)
            {
                if (cancelQueue[this.Context.ConnectionId])
                {
                    cancelQueue.Remove(this.Context.ConnectionId);
                    return;
                }

                string msg = GetNewMessage(uid.ToString());
                Caller.newMessage(msg);  //push new message to client

                string notice = GetSystemNotification();
                if (!string.IsNullOrEmpty(notice))
                    Clients.notify(notice);
            }
        }

        public System.Threading.Tasks.Task Disconnect()
        {
            if (cancelQueue.Keys.Contains(this.Context.ConnectionId))
            {
                cancelQueue[this.Context.ConnectionId] = true;
            }
            return null;
        }

        #region User Message Generator
        private string GetNewMessage(string uid)
        {
            Thread.Sleep(3000);
            return string.Format("message from xxx to {0}  ({1})", uid, DateTime.Now);
        }

        private string GetSystemNotification()
        {
            if (new Random().Next(6) >= 5)
                return "system will shutdown for maintenance";
            else
                return string.Empty;
        }
        #endregion
    }
}